package service

import (
	"context"
	"mini-app/config/mysql"
	"mini-app/internal/dao"
	"strings"

	"github.com/samber/lo"
)

type PublishDevice struct{}

// ================== advertisingc.相关Req/Rsp结构体 ==================
type PublishDeviceGroupListReq struct {
	Name  string `json:"name"`
	Page  int32  `json:"page"`
	Limit int32  `json:"limit"`
}

type PublishDeviceGroupListRsp struct {
	Code int32                         `json:"code"`
	Msg  string                        `json:"msg"`
	Data PublishDeviceGroupListRspData `json:"data"`
}

type PublishDeviceGroupListRspData struct {
	Count int64                                      `json:"count"`
	List  []PublishDeviceGroupListRspDeviceGroupList `json:"list"`
}

type PublishDeviceGroupListRspDeviceGroupList struct {
	Id        string `json:"id"`
	Name      string `json:"name"`
	CreatedAt int32  `json:"created_at"`
	UpdatedAt int32  `json:"updated_at"`
}

type PublishDeviceGroupSaveReq struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}

type PublishDeviceGroupSaveRsp struct {
	Code int32  `json:"code"`
	Msg  string `json:"msg"`
}

type PublishDeviceGroupDeleteReq struct {
	Id string `json:"id"`
}

type PublishDeviceGroupDeleteRsp struct {
	Code int32  `json:"code"`
	Msg  string `json:"msg"`
}

type PublishDeviceGroupManageReq struct {
	Id      string `json:"id"`
	Devices string `json:"devices"`
}

type PublishDeviceGroupManageRsp struct {
	Code int32  `json:"code"`
	Msg  string `json:"msg"`
}

type PublishDeviceListReq struct {
	Id string `json:"id"`
}

type PublishDeviceListRsp struct {
	Code int32                    `json:"code"`
	Msg  string                   `json:"msg"`
	Data PublishDeviceListRspData `json:"data"`
}

type PublishDeviceListRspData struct {
	Count int64                                   `json:"count"`
	List  []PublishDeviceListRspPublishDeviceList `json:"list"`
}

type PublishDeviceListRspPublishDeviceList struct {
	Id        string `json:"id"`
	Name      string `json:"name"`
	CreatedAt int32  `json:"created_at"`
}

// ================== END ==================

// 投放设备组列表
func (PublishDevice) PublishDeviceGroupList(ctx context.Context, req PublishDeviceGroupListReq) (PublishDeviceGroupListRsp, error) {
	res := PublishDeviceGroupListRsp{}
	db := mysql.NewDB()
	DeviceGroupList, count, _ := dao.PublishDeviceGroup{}.PublishDeviceGroupList(ctx, db, req.Name, int(req.Page), int(req.Limit))
	res.Data = PublishDeviceGroupListRspData{}
	res.Data.Count = count
	for _, v := range DeviceGroupList {
		var item = PublishDeviceGroupListRspDeviceGroupList{}
		item.Id = v.ID
		item.Name = v.Name
		item.CreatedAt = int32(v.CreatedAt)
		item.UpdatedAt = int32(v.UpdatedAt)
		res.Data.List = append(res.Data.List, item)
	}
	return res, nil
}

// 投放设备组新增编辑
func (PublishDevice) PublishDeviceGroupSave(ctx context.Context, req PublishDeviceGroupSaveReq) (PublishDeviceGroupSaveRsp, error) {
	res := PublishDeviceGroupSaveRsp{}
	res.Code = -1
	if strings.TrimSpace(req.Name) == "" {
		res.Msg = "设备分组名称不能为空"
		return res, nil
	}
	db := mysql.NewDB()
	if req.Id == "" { // 新增
		nameExist := dao.PublishDeviceGroup{}.SameNameExist(ctx, db, req.Name, "")
		if nameExist != 0 {
			res.Msg = "设备分组名称已经存在"
			return res, nil
		}
		dao.PublishDeviceGroup{}.Create(ctx, db, req.Name)
	} else { // 编辑
		count := dao.PublishDeviceGroup{}.DeviceGroupExist(ctx, db, req.Id)
		if count == 0 {
			res.Msg = "设备分组不存在"
			return res, nil
		}

		nameExist := dao.PublishDeviceGroup{}.SameNameExist(ctx, db, req.Name, req.Id)
		if nameExist != 0 {
			res.Msg = "设备分组名称已经存在"
			return res, nil
		}
		dao.PublishDeviceGroup{}.Update(ctx, db, req.Id, strings.TrimSpace(req.Name))
	}
	res.Code = 0
	return res, nil
}

// 投放设备组删除
func (PublishDevice) PublishDeviceGroupDelete(ctx context.Context, req PublishDeviceGroupDeleteReq) (PublishDeviceGroupDeleteRsp, error) {
	res := PublishDeviceGroupDeleteRsp{}
	if strings.TrimSpace(req.Id) == "" {
		res.Code, res.Msg = -1, "设备分组必须"
		return res, nil
	}
	db := mysql.NewDB()
	count := dao.PublishDeviceGroup{}.DeviceGroupExist(ctx, db, req.Id)
	if count == 0 {
		res.Code = -1
		res.Msg = "设备分组不存在"
		return res, nil
	}

	// //判断设备分组是否在使用中
	// _, GroupInUseCount := dao.MerchantPublishDeviceGroup{}.Detail(ctx, db, "", req.Id)
	// if GroupInUseCount > 0 {
	// 	res.Code = -1
	// 	res.Msg = "设备分组正在使用中,无法删除"
	// 	return res, nil
	// }
	dao.PublishDeviceGroup{}.Delete(ctx, db, req.Id)
	return res, nil
}

// 投放设备组配置设备
func (PublishDevice) PublishDeviceGroupManage(ctx context.Context, req PublishDeviceGroupManageReq) (PublishDeviceGroupManageRsp, error) {
	res := PublishDeviceGroupManageRsp{}
	if strings.TrimSpace(req.Id) == "" {
		res.Code = -1
		res.Msg = "设备分组必须"
		return res, nil
	}

	db := mysql.NewDB()
	count := dao.PublishDeviceGroup{}.DeviceGroupExist(ctx, db, req.Id)
	if count == 0 {
		res.Code = -1
		res.Msg = "设备分组不存在"
		return res, nil
	}
	OldDeviceList := dao.PublishDevice{}.GetRobotNameList(ctx, db, req.Id)
	// 新增 删除
	//deleteDevice  是 DeviceList没有的 即 需删除
	//addDevice  是 OldDeviceList没有的 即 新增的
	DeviceList := strings.Split(req.Devices, ",")
	deleteDevice, addDevice := lo.Difference(OldDeviceList, DeviceList)

	// // 投放设备组关联的商户列表
	// var MerchantList = []string{}
	// merchantGroupList, _, _ := dao.MerchantPublishDeviceGroup{}.List(ctx, db, "", req.Id, 0, 0)
	// for _, v := range merchantGroupList {
	// 	MerchantList = append(MerchantList, v.MerchantID)
	// }
	// // 判断设备是否被计划使用，如被使用不允许删除
	// if len(MerchantList) > 0 {
	// 	// 查找所有计划
	// 	scheduleList, _, _ := dao.PublishSchedule{}.List(ctx, db, strings.Join(MerchantList, ","), "", "", "", 0, 0, 0, 0, 0, 0)
	// 	var scheduleIDList []string
	// 	for _, v := range scheduleList {
	// 		if v.Status != 5 && v.Status != 6 {
	// 			scheduleIDList = append(scheduleIDList, v.ID)
	// 		}
	// 	}
	// 	if len(deleteDevice) > 0 {
	// 		// 查找计划中包含删除设备的计划 [true 不包含待删除的]
	// 		_, UsingDeviceCount, _ := dao.PublishScheduleDevice{}.List(ctx, db, strings.Join(MerchantList, ","), strings.Join(scheduleIDList, ","), strings.Join(deleteDevice, ","), 0, 0, 0, true, 0, 0)
	// 		if UsingDeviceCount > 0 {
	// 			res.Code = -1
	// 			res.Msg = "设备正在使用中，无法删除"
	// 			return res, nil
	// 		}
	// 	}
	// }
	if len(deleteDevice) > 0 {
		delErr := dao.PublishDevice{}.DeleteGroupDevice(ctx, db, req.Id, strings.Join(deleteDevice, ","))
		if delErr != nil {
			res.Code = -1
			res.Msg = delErr.Error()
			return res, nil
		}
	}
	// 新增设备
	for _, v := range addDevice {
		dao.PublishDevice{}.Create(ctx, db, v, req.Id)
	}
	return res, nil
}

// 投放设备组设备列表
func (PublishDevice) PublishDeviceList(ctx context.Context, req PublishDeviceListReq) (PublishDeviceListRsp, error) {
	res := PublishDeviceListRsp{}
	if strings.TrimSpace(req.Id) == "" {
		res.Code = -1
		res.Msg = "设备分组必须"
		return res, nil
	}
	db := mysql.NewDB()
	count := dao.PublishDeviceGroup{}.DeviceGroupExist(ctx, db, req.Id)
	if count == 0 {
		res.Code = -1
		res.Msg = "设备分组不存在"
		return res, nil
	}
	res.Data = PublishDeviceListRspData{}
	DeviceList, count := dao.PublishDevice{}.GetDeviceListByGroupID(ctx, db, req.Id)
	res.Data.Count = count
	for _, v := range DeviceList {
		var item = PublishDeviceListRspPublishDeviceList{}
		item.Id = v.ID
		item.Name = v.RobotName
		item.CreatedAt = int32(v.CreatedAt)
		res.Data.List = append(res.Data.List, item)
	}
	return res, nil
}
